﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.SessionState;
using System.Drawing;
using System.Drawing.Imaging;

public partial class Ajax_ForecastIdentifyingCode : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Print();
        }
    }
    protected static void Print()
    {
        HttpContext.Current.Response.ContentType = "image/gif";

        Random rd = new Random(); //创建随机数生成器

        string sn = "";
        int number = 0;
        for (int i = 0; i < 4; i++) //校验码长度为4
        {
            //随机的整数
            number = rd.Next();

            //字符从0-9,A-Z中随机产生,对应的ASCII码分别为
            //48-57,65-90
            number = number % 36;
            if (number < 10)
            {
                number += 48;
            }
            else
            {
                number += 55;
            }
            sn += ((char)number).ToString();
        }

        System.Web.HttpContext.Current.Session["forecastYzm"] = sn;
        System.Web.HttpContext.Current.Session.Timeout = 30;
        Bitmap bmp = new Bitmap(sn.Length * 25, 25);
        Graphics g = Graphics.FromImage(bmp);
        g.FillRectangle(Brushes.White, 0, 0, bmp.Width, bmp.Height);

        for (int i = 0; i < 20; i++)
        {
            //Color表示一种ARGB 颜色（alpha 默认为255 完全不透明，红，绿，蓝）这样让验证码是不同的颜色。
            Color c = Color.FromArgb(rd.Next(238), rd.Next(218), rd.Next(241));
            Pen p = new Pen(c, 1);
            int x1 = rd.Next(bmp.Width);
            int y1 = rd.Next(25);
            int x2 = rd.Next(bmp.Width);
            int y2 = rd.Next(25);
            if (i % 50 == 0)
            {
                g.DrawLine(p, x1, y1, x2, y2);//绘制不同结构的线,即验证码的干扰线
            }
            else
            {
                g.DrawPie(p, x1, y1, 1, 1, x1, y1);//绘制不同结构的线,即验证码的干扰线
            }
        }
        Brush[] color = { Brushes.SaddleBrown };
        for (int i = 0; i < sn.Length; i++)
        {
            int x = rd.Next(5) + i * 25;
            int y = rd.Next(5);
            //用指定的画笔和字体在指定的区域绘制指定的文本字符串。
            g.DrawString(sn[i].ToString(), new Font("黑体", 16, FontStyle.Bold), color[rd.Next(color.Length)], x, y);
        }
        bmp.Save(HttpContext.Current.Response.OutputStream, ImageFormat.Gif);//将该图像保存的指定的流
        g.Dispose();//释放由graphics所有的资源。
        bmp.Dispose();// 释放由Image使用的所有资源。
                      //HttpContext.Current.Response.End();
    }
}